package org.jflame.auth.session.web;

import org.jflame.auth.session.SessionAdapter;

import java.util.Optional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class HttpSessionAdapter implements SessionAdapter {

    private HttpServletRequest request;

    public HttpSessionAdapter(HttpServletRequest request) {
        this.request = request;
    }

    protected Optional<HttpSession> getSession(boolean create) {
        return Optional.ofNullable(request.getSession(create));
    }

    protected HttpSession getSession() {
        return request.getSession(true);
    }

    @Override
    public Optional<String> getSessionId(boolean create) {
        Optional<HttpSession> session = getSession(create);
        if (session.isPresent()) {
            return Optional.of(session.get()
                    .getId());
        }
        return Optional.empty();
    }

    @Override
    public Optional<Object> getAttribute(String name) {
        Optional<HttpSession> session = getSession(false);
        if (session.isPresent()) {
            return Optional.of(session.get()
                    .getAttribute(name));
        }
        return Optional.empty();
    }

    @Override
    public void setAttribute(String name, Object value) {
        getSession().setAttribute(name, value);
    }

    @Override
    public void invalidate() {
        Optional<HttpSession> session = getSession(false);
        if (session.isPresent()) {
            session.get()
                    .invalidate();
        }
    }

    @Override
    public void renew() {
        HttpSession session = getSession();
        if (!session.isNew()) {
            request.changeSessionId();
        }
    }

}
